package cn.itzzx.beans.factory;

import cn.itzzx.annotation.Autowired;
import cn.itzzx.annotation.Service;
import cn.itzzx.util.TransactionManager;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.SQLException;
import java.util.Set;

/**
 * TODO 写点注视啦
 *
 * @author Martin
 * @date 2020-05-04
 * @see 1.0
 */
@Service
public class ProxyFactory {

    @Autowired
    private TransactionManager transactionManager;


    /**
     * @Transactional 声明在类上的处理
     * @param obj
     * @return
     */
    public Object getJdkProxy(Object obj) {

        //获取代理对象
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    //事务控制处理
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        return transaction(method, obj, args);
                    }
                });
    }

    /**
     * @Transactional 声明在类上的处理
     * @param obj
     * @return
     */
    public Object getCglibProxy(Object obj) {
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                return transaction(method, obj, objects);
            }
        });

    }



    /**
     * @Transactional 声明在方法上的处理
     * @param obj
     * @param methods
     * @return
     */
    public Object getJdkProxy(Object obj, Set<Method> methods) {
        // 获取代理对象
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if (methods.contains(method)) {
                            return transaction(method, obj, args);
                        }
                        return method.invoke(obj, args);
                    }
                });
    }

    /**
     * @Transactional 声明在方法上的处理 使用cglib动态代理生成代理对象
     *
     * @param obj 委托对象
     * @return
     */
    public Object getCglibProxy(Object obj, Set<Method> methods) {
        return Enhancer.create(obj.getClass(), new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                if (methods.contains(method)) {
                    return transaction(method, obj, objects);
                }
                return method.invoke(obj, objects);
            }
        });
    }


    /**
     * 事务控制
     *
     * @param method 目标方法
     * @param target 目标对象
     * @param args   参数
     * @return
     */
    private Object transaction(Method method, Object target, Object[] args) throws SQLException, InvocationTargetException, IllegalAccessException {
        Object result = null;
        try {
            // 开启事务(关闭事务的自动提交)
            transactionManager.beginTransaction();
            result = method.invoke(target, args);
            // 提交事务
            transactionManager.commit();
        } catch (Exception e) {
            e.printStackTrace();
            // 回滚事务
            transactionManager.rollback();

            // 抛出异常便于上层servlet捕获
            throw e;
        }
        return result;
    }

}
